﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Warehouse.API.Applcation.Command.Movelibrary;
using Warehouse.Domain;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;

namespace Warehouse.API.Applcation.CommandHandlers.MovelibraryCommandHandlers
{
    public class MovelibraryCreateCommandHandlers:IRequestHandler<MovelibraryCreateCommand,int>
    {
        IMovelibraryRepository IRep;
        EFCoreDBcontext dbContext;
        IMoveProductRepository ipRep;
        IMapper _mapper;

        public MovelibraryCreateCommandHandlers(IMovelibraryRepository iRep, EFCoreDBcontext dbContext, IMoveProductRepository ipRep, IMapper mapper)
        {
            IRep = iRep;
            this.dbContext = dbContext;
            this.ipRep = ipRep;
            _mapper = mapper;
        }

        public async Task<int> Handle(MovelibraryCreateCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    var s = _mapper.Map<Movelibrary>(request.addDto);

                    //先加移库
                    await IRep.AddAsync(s);

                    foreach (var item in request.addDto.AllProducs)
                    {
                        MoveProduct detail = new MoveProduct
                        {
                            ProductsID = item.ProductsID,
                            MovelibraryCode = s.MovelibraryCode,
                            MoveProductNum = item.MoveProductNum,
                            Movelocation = item.Movelocation
                        };
                        await ipRep.AddAsync(detail);
                    }

                    // 提交事务
                    await tran.CommitAsync();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    await tran.RollbackAsync();
                    throw;
                }
            }
        }
    }
}
